package com.xusheng.cli.controller.back;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xusheng.cli.common.base.Attachment;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.enums.FileDirectoryEnum;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.advertModule.Advert;
import com.xusheng.cli.entity.advertModule.AdvertPosition;
import com.xusheng.cli.req.AdvertQueryReq;
import com.xusheng.cli.req.PositionQueryReq;
import com.xusheng.cli.service.AdvertPositionService;
import com.xusheng.cli.service.AdvertService;
import com.xusheng.cli.tools.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 广告相关接口
 *
 * @author lyh
 * @since 2023-04-25 13:23
 */
@RestController
@RequestMapping("/api/v1/advert")
public class AdvertController {

    @Resource
    private AdvertService advertService;
    @Resource
    private AdvertPositionService positionService;

    @Value("${serverIp}")
    private String serverIp;

    /**
     * 通过条件获取广告位置
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("/position")
    public Result<MyPage<AdvertPosition>> list(PositionQueryReq req) {
        MyPage<AdvertPosition> page = positionService.lambdaQuery()
                .orderByDesc(AdvertPosition::getCreateTime)
                .page(req.getPage());
        return Result.success(page);
    }

    /**
     * 获取所有广告列表位置
     *
     * @return 返回结果
     */
    @GetMapping("/position/all")
    public Result<List<AdvertPosition>> all() {
        List<AdvertPosition> list = positionService.lambdaQuery()
                .orderByDesc(AdvertPosition::getCreateTime)
                .list();
        return Result.success(list);
    }

    /**
     * 保存广告位置
     *
     * @param position 广告位置
     * @return 返回结果
     */
    @PostMapping("/position")
    public Result<Object> save(@Validated(Save.class) @RequestBody AdvertPosition position) {
        return Result.isSuccess(positionService.save(position));
    }

    /**
     * 更新广告位置
     *
     * @param position 广告位置
     * @return 返回结果
     */
    @PutMapping("/position")
    public Result<Object> update(@Validated(Update.class) @RequestBody AdvertPosition position) {
        return Result.isSuccess(positionService.updateById(position));
    }

    /**
     * 通过id获取广告位置
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/position/{id}")
    public Result<AdvertPosition> info(@PathVariable long id) {
        return Result.success(positionService.getById(id));
    }

    /**
     * 通过id删除广告位置
     *
     * @param id 编号
     * @return 返回结果
     */
    @DeleteMapping("/position/{id}")
    public Result<Object> deleted(@PathVariable long id) {
        return Result.isSuccess(positionService.removeById(id));
    }

    /**
     * 通过条件查询广告
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public Result<MyPage<Advert>> list(@Validated AdvertQueryReq req) {
        MyPage<Advert> page = advertService.lambdaQuery()
                .eq(Advert::getPositionId, req.getPositionId())
                .orderByDesc(Advert::getCreateTime)
                .page(req.getPage());
        return Result.success(page);
    }

    /**
     * 保存广告
     *
     * @param advert 广告
     * @param file   广告图
     * @return 返回结果
     */
    @PostMapping("/save")
    public Result<Object> save(@Validated(Save.class) Advert advert, MultipartFile file) {
        Attachment attachment = FileUtils.uploadSingleFile(file, FileDirectoryEnum.AD);
        advert.setFilename(attachment.getPath());
        advert.setImage(serverIp + attachment.getUrl());
        return Result.isSuccess(advertService.save(advert));
    }

    /**
     * 更新广告
     *
     * @param advert 广告
     * @param file   广告图
     * @return 返回结果
     */
    @PostMapping("/update")
    public Result<Object> update(@Validated(Update.class) Advert advert,
                                 @RequestParam(required = false) MultipartFile file) {
        // 获取原图片路径
        String path = advertService.getById(advert.getId()).getFilename();
        LambdaUpdateWrapper<Advert> update = Wrappers.<Advert>lambdaUpdate()
                .set(Advert::getUrl, advert.getUrl())
                .set(Advert::getTitle, advert.getTitle())
                .set(Advert::getDescription, advert.getDescription())
                .eq(Advert::getId, advert.getId());
        if (file != null && !file.isEmpty()) {
            Attachment attachment = FileUtils.uploadSingleFile(file, FileDirectoryEnum.AD);
            update.set(Advert::getFilename, attachment.getPath());
            update.set(Advert::getImage, serverIp + attachment.getUrl());
            // 删除原图片
            FileUtil.del(path);
        }
        return Result.isSuccess(advertService.update(new Advert(), update));
    }

    /**
     * 通过id获取广告
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public Result<Advert> adInfo(@PathVariable long id) {
        return Result.success(advertService.getById(id));
    }

    /**
     * 通过id删除广告
     *
     * @param id 编号
     * @return 返回结果
     */
    @DeleteMapping("/{id}")
    public Result<Object> adDelete(@PathVariable long id) {
        return Result.isSuccess(advertService.removeById(id));
    }
}
